/*
 * Copyright (c) 2018 Hitevision
 */

package tw.com.hitevision.whiteboard.android.display;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

import com.internal.i.solution.device.IsDeviceManager;
import com.ist.android.tv.IstCommonManager;
import com.ist.android.tv.IstEventManager;

import hht.lib.xmsf.HHTCommand;
import tw.com.hitevision.whiteboard.android.MainActivity;
import tw.com.hitevision.whiteboard.android.Props;
import tw.com.hitevision.whiteboard.android.R;
import com.xbh.sdk3.Picture.PictureHelper;
import com.xbh.unf.client.API;


/**
 * This class controls the display backlight based on touch events.
 */
public class BacklightManager {
    private static final String TAG = BacklightManager.class.getSimpleName();

    private static final int BACKLIGHT_DIM_INTERVAL = 1000; // ms
    private static final int BACKLIGHT_DIM_UPDATE_RATE = 16; // ms

    private BacklightThread bThread;

    private boolean isSupported;

    public BacklightManager(Context context) {
        if (!Props.getFlavorChipset().equals(Props.Flavor.Chipset.Mstar)&&!Props.getFlavorChipset().equals(Props.Flavor.Chipset.Optoma)&&!Props.getFlavorChipset().equals(Props.Flavor.Chipset.Amlogic)) {
            isSupported = false;
            return;
        }

        final Resources res = context.getResources();
        final int backlightDimmedValue = res.getInteger(R.integer.backlight_writing_eye_protection_mode);
        final int backlightDimmedTimeOut = res.getInteger(R.integer.backlight_writing_eye_protection_time_out);
        final int backlightDimmingThresholdValue = res.getInteger(R.integer.backlight_writing_eye_protection_threshold);

        bThread = new BacklightThread(context.getApplicationContext(), backlightDimmedValue, backlightDimmedTimeOut, backlightDimmingThresholdValue);
        bThread.setRunning(true);
        bThread.start();

        isSupported = true;
    }

    private static class BacklightThread extends Thread {
        private final int backlightDimmedValue;
        private final int backlightDimmingThresholdValue;
        private final int backlightDimmedTimeOut;
        private IstCommonManager istCommonManager;
        private IstEventManager istEventManager;
        private final Context context;
        private final DisplayManager displayManager;

        private boolean running;
        public PictureHelper pictureHelper;
        private volatile int normalValue;
        private volatile long dimStart;
        private volatile long restoreStart;
        private volatile int state;

        private long temp = 0;
        private int backlight;
        private int delta;

        private BacklightThread(Context context,
                                int backlightDimmedValue,
                                int backlightDimmedTimeOut,
                                int backlightDimmingThresholdValue) {
            this.context = context;
            this.backlightDimmedValue = backlightDimmedValue;
            this.backlightDimmedTimeOut = backlightDimmedTimeOut;
            this.backlightDimmingThresholdValue = backlightDimmingThresholdValue;


            displayManager = DisplayManager.getInstance();
            state = BACKLIGHT_NORMAL;
            normalValue = displayManager.getBacklight(context);

            if (Props.getFlavorChipset().equals(Props.Flavor.Chipset.Amlogic)){
                if (pictureHelper == null) {
                    API.getInstance().init(context.getApplicationContext());
                    pictureHelper = new PictureHelper();
                }
            }

        }

        private void setRunning(boolean running) {
            this.running = running;
        }

        private void onTouchDown() {
            log("onTouchDown: state=" + state);
            temp = System.currentTimeMillis();
            switch (state) {
                case BACKLIGHT_NORMAL: {
                    // save current backlight and dim
                    normalValue = displayManager.getBacklight(context);
                    log("- normalValue=" + normalValue);
                    if (normalValue > backlightDimmingThresholdValue) {
                        dimStart = System.currentTimeMillis();
                        restoreStart = Long.MAX_VALUE;
                        backlight = normalValue;
                        delta = 1;
                        state = BACKLIGHT_DIMMING;
                    }
                    break;
                }
                case BACKLIGHT_DIMMED: {
                    restoreStart = Long.MAX_VALUE;
                    break;
                }
                case BACKLIGHT_RESTORING: {
                    // stop restoring and start dimming
                    dimStart = restoreStart;
                    restoreStart = Long.MAX_VALUE;
                    delta = 1;

                    state = BACKLIGHT_DIMMING;
                    break;
                }
                case BACKLIGHT_DIMMING: {
                    // do nothing
                }
            }
        }

        private void onTouchUp() {
            switch (state) {
                case BACKLIGHT_NORMAL:
                case BACKLIGHT_RESTORING: {
                    // do nothing
                    break;
                }
                case BACKLIGHT_DIMMING:
                case BACKLIGHT_DIMMED: {
                    // schedule restoring backlight after a time out
                    restoreStart = System.currentTimeMillis() + backlightDimmedTimeOut;
                    break;
                }
            }
        }

        private void cancel() {
            if (state != BACKLIGHT_NORMAL) {
                state = BACKLIGHT_NORMAL;
                displayManager.setBacklight(context, normalValue);
                displayManager.saveBacklightToSettings(context, normalValue);
            }
        }

        @Override
        public void run() {
            while (running) {
                switch (state) {
                    case BACKLIGHT_NORMAL: {
                        // do nothing
                        break;
                    }
                    case BACKLIGHT_DIMMING: {
                        /*
                        final int delta = BACKLIGHT_DIM_INTERVAL - (int) (System.currentTimeMillis() - dimStart);
                        final float rate;
                        if (delta > 0) {
                            rate = 1.0f * delta / BACKLIGHT_DIM_INTERVAL;
                        } else {
                            rate = 0;
                        }

                        displayManager.setBacklight(backlightDimmedValue
                                + (int) ((normalValue - backlightDimmedValue) * rate));

                        if (delta <= 0) {
                            state = BACKLIGHT_DIMMED;
                        }
                        */

                        backlight -= delta;

                        if (backlight <= backlightDimmedValue) {
                            backlight = backlightDimmedValue;
                            state = BACKLIGHT_DIMMED;
                        }

                        if (Props.getFlavorChipset().equals(Props.Flavor.Chipset.Mstar)) {
                            displayManager.setBacklight(context, backlight);
                        } else if (Props.getFlavorChipset().equals(Props.Flavor.Chipset.Amlogic)) {
//                            HHTCommand.getInstance(context).sendSingleCommand("brightness="+backlight);
                            //                    pictureHelper.setBacklightNoSave(backlight);
                            pictureHelper.setBacklight(backlight);
                            log("BACKLIGHT_DIMMING  backlight: = " + backlight);
                        } else {
                            if (isBrightnessModeAuto()) {
//                                istEventManager.setBacklight(backlight);
                                IsDeviceManager.getInstance().setBacklight(backlight);
                            }
                        }
                        break;
                    }
                    case BACKLIGHT_DIMMED: {
                        if (System.currentTimeMillis() >= restoreStart) {
                            temp = 0;
                            state = BACKLIGHT_RESTORING;
                        }
                        break;
                    }
                    case BACKLIGHT_RESTORING: {
                        /*
                        final int delta = BACKLIGHT_DIM_INTERVAL - (int) (System.currentTimeMillis() - restoreStart);
                        final float rate;
                        if (delta > 0) {
                            rate = 1.0f * delta / BACKLIGHT_DIM_INTERVAL;
                        } else {
                            rate = 0;
                        }

                        displayManager.setBacklight(normalValue
                                - (int) ((normalValue - backlightDimmedValue) * rate));

                        if (delta <= 0) {
                            state = BACKLIGHT_NORMAL;
                        }
                        */

                        backlight += delta;

                        if (backlight >= normalValue) {
                            backlight = normalValue;

                            state = BACKLIGHT_NORMAL;
                            if (Props.getFlavorChipset().equals(Props.Flavor.Chipset.Mstar)) {
                                displayManager.saveBacklightToSettings(context, normalValue);
                            }
                        }

                        if (Props.getFlavorChipset().equals(Props.Flavor.Chipset.Mstar)) {
                            displayManager.setBacklight(context, backlight);
                        } else if (Props.getFlavorChipset().equals(Props.Flavor.Chipset.Amlogic)) {
//                            HHTCommand.getInstance(context).sendSingleCommand("brightness="+backlight);
//                            pictureHelper.setBacklightNoSave(backlight);
                            pictureHelper.setBacklight(backlight);
                            log("BACKLIGHT_RESTORING backlight:" + backlight);
                        } else {
                            if (isBrightnessModeAuto()) {
//                                istEventManager.setBacklight(backlight);
                                IsDeviceManager.getInstance().setBacklight(backlight);
                            }
                        }
                        break;
                    }
                }

                /*
                try {
                    sleep(BACKLIGHT_DIM_UPDATE_RATE);
                } catch (InterruptedException e) {
                    e.printStackTrace();

                    cancel();
                    running = false;
                }
                */

                // sleep for 1 ms, otherwise cpu usage will be high
                try {
                    sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Notifies that a touch down event occurred.
     */
    private static boolean isBrightnessModeAuto() {
        return true;
//            return (istCommonManager != null && istCommonManager.getBrightnessMode().equals("auto"));
    }

    public void onTouchDown() {
        if (!isSupported) {
            return;
        }

        bThread.onTouchDown();
    }

    /**
     * Notifies that a touch up event occurred.
     */
    public void onTouchUp() {
        if (!isSupported) {
            return;
        }

        bThread.onTouchUp();
    }

    /**
     * Cancels dimming and restores backlight to original value.
     */
    public void cancel() {
        if (!isSupported) {
            return;
        }

        bThread.cancel();
    }

    /**
     * Closes this manager.  This instance cannot be reused.
     */
    public void close() {
        if (!isSupported) {
            return;
        }

        bThread.setRunning(false);
        bThread.interrupt();
    }

    // states for backlight dimming
    private static final int BACKLIGHT_NORMAL = 0;
    private static final int BACKLIGHT_DIMMING = 1;
    private static final int BACKLIGHT_RESTORING = 2;
    private static final int BACKLIGHT_DIMMED = 3;

    private static void log(String msg) {
        Log.d(TAG, msg);
    }
}
